from user.models import UserProfile

from server.settings import JSON_TOKEN_KEY

import json
import time
import hashlib
import jwt
from utils.return_data import result_error, resultError, result_success, resultSuccess


def tokens(request):
    if request.method != 'POST':
        return resultError('111', '请使用post方式请求')

    json_str = request.body
    json_obj = json.loads(json_str)

    username = json_obj['username']
    password = json_obj['password']

    user = UserProfile.objects.filter(username=username)

    if len(user) == 1:
        user = user[0]
        password_hash_md5 = hashlib.md5()
        password_hash_md5.update(password.encode())
        if user.password != password_hash_md5.hexdigest():
            return resultError('333', '密码错误')
        else:
            token = makeToken(username)
            result = {
                'username': username,
                'token': token
            }
            return resultSuccess('200', '登录成功', result)

    elif len(user) == 0:
        return resultError('222', '用户名不存在')


# 生成token
# expire是token的有效期
def makeToken(username, expire=3600 * 24):
    key = JSON_TOKEN_KEY
    now_t = time.time()
    payload_data = {
        'username': username,
        'exp': now_t + expire
    }

    return jwt.encode(payload_data, key, algorithm='HS256')
